package com.xspace.android.imcommon.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

	private static final String TAG = "DBHelper";

	private static final String DB_NAME = "xspace_message_db";

	//添加推送未读字段 数据库版本升级4-->5
	//添加群聊数据表 数据库版本升级5-->6
	//添加群聊数据表 数据库版本升级6-->7
	//修改会话列表数据表 数据库版本升级7-->8
	//修改单聊消息数据表 数据库版本升级7-->8
	//添加群消息平台号字段 数据库版本升级8-->9
	//添加文件上传表 数据库版本升级9-->10
	private static final int DATABASE_VERSION = 10;

	private static DBHelper mDBHelper;

	public static DBHelper getInstance(Context context) {
		if (mDBHelper == null) {
			mDBHelper = new DBHelper(context);
		}
		return mDBHelper;
	}

	private DBHelper(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(TAG, "onCreate");
		createTable(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i(TAG, "onUpgrade");
		dropTableFromVersion(db);
		createTable(db);
	}

	private void dropTableFromVersion(SQLiteDatabase db) {
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + ImUserDb.TABLE_NAME);
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + MessageDb.TABLE_NAME);
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + MucChatMessageDB.TABLE_NAME);
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + RoomDB.TABLE_NAME);
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + FriendDb.TABLE_NAME);
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + PushDb.TABLE_NAME);

		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + new InviteSMSDBBiz().getTableName());
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + new LAWSMSDBBiz().getTableName());
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + new QACSMSDBBiz().getTableName());
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + new ResumeSMSDBBiz().getTableName());
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + new SMSDBBiz().getTableName());
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " + new SPDMSMSDBBiz().getTableName());
		execSQLASLevel(db, "DROP TABLE  IF EXISTS  " +  FileUploadDb.TABLE_NAME);
	}

	private void createTable(SQLiteDatabase db) {
		db.execSQL(MessageDb.CREATE_TABLE);
		db.execSQL(MucChatMessageDB.CREATE_TABLE);
		db.execSQL(RoomDB.CREATE_TABLE);
		db.execSQL(ImUserDb.CREATE_TABLE);
		db.execSQL(FriendDb.CREATE_TABLE);
		db.execSQL(PushDb.CREATE_TABLE);

		db.execSQL(new InviteSMSDBBiz().getTable());
		db.execSQL(new LAWSMSDBBiz().getTable());
		db.execSQL(new QACSMSDBBiz().getTable());
		db.execSQL(new ResumeSMSDBBiz().getTable());
		db.execSQL(new SMSDBBiz().getTable());
		db.execSQL(new SPDMSMSDBBiz().getTable());
		db.execSQL(FileUploadDb.CREATE_TABLE);
	}

	public static void execSQLASLevel(SQLiteDatabase db, String sql) {
		try {
			db.execSQL(sql);
		} catch (Exception excp) {
			Log.d("error", excp.getMessage() + "table:" + sql);
		}
	}
}